package com.ken.gateway.Filter;

import com.auth0.jwt.interfaces.DecodedJWT;
import com.ken.common.utils.JWTUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;
@Slf4j
@Component
public class MyGlobalFilter implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取request
        ServerHttpRequest request = exchange.getRequest();
        System.out.println(request.getPath()+"请求体："+request.getBody().toString()+"请求头"+request.getHeaders());
        //判断是否要做登录拦截
        if (isExclude(request.getPath().toString())){
            log.info("登录或注册操作直接放行");
            return chain.filter(exchange);
        }
        //获取token
        String Token="";
        List<String> token = request.getHeaders().get("Token");
        if (token != null && !token.isEmpty()){
            Token = token.get(0);
        }
        try {
            //校验并登录
            DecodedJWT decodedJWT = JWTUtil.ParseJWt(Token);
        }catch (Exception e){
            // 拦截，设置响应状态码
            ServerHttpResponse response = exchange.getResponse();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        //传递用户信息

        //放行
        log.info("验证成功放行");
        return chain.filter(exchange);
    }
    //保证是最后一个执行
    @Override
    public int getOrder(){
        //值越小优先级越高
        return 0;
    }
    private boolean isExclude(String path){
        // 使用String的contains方法检查路径是否包含"login"或"register"
        return path != null && (path.contains("login") || path.contains("register") || path.contains("Captcha") || path.contains("sendMessage") || path.contains("Register") || path.contains("Login") || path.contains("post_img")) ;
    }
}
